﻿using Newtonsoft.Json.Linq;

namespace ChatGPT.UI;
public class ChatGPTService
{
    private readonly ChatGPTClient client;

    public ChatGPTService(ChatGPTClient client)
    {
        this.client = client;
    }

    /// <summary>
    /// 编码
    /// </summary>
    public async Task<string> Coding(string requirement)
    {
        var system = TextHelper.ReaderText("system.txt");
        var technical = TextHelper.ReaderText("technical.txt");
        var sampleCode = TextHelper.ReaderText("sampleCode.txt");
        var prompt = $"技术规范\r\n```\r\n{technical}\r\n```\r\n示例代码\r\n```\r\n{sampleCode}\r\n```\r\n业务需求\r\n```\r\n{requirement}\r\n```";
        return await GetCompletion(system, prompt);
    }

    /// <summary>
    /// 需求提示词优化
    /// </summary>
    public async Task<string> RequirementOptimize(string requirement)
    {
        var system = "You are a prompt word engineer, and you need to optimize the prompt words. Explain the reasons for optimization.please reply in chinese";
        var technical = TextHelper.ReaderText("technical.txt");
        var prompt = $"下列提示词用于ChatGPT在技术规范下生成代码的业务需求.\r\n技术规范\r\n```\r\n{technical}\r\n```\r\n需要优化的提示词:\r\n```\r\n{requirement}\r\n```";
        return await GetCompletion(system, prompt);
    }

    public async Task<string> technicalOptimize(string technical)
    {
        var system = "You are a prompt word engineer, and you need to optimize the prompt words. Explain the reasons for optimization.please reply in chinese";

        var prompt = $"下列的提示词用于 ChatGPT用于代码生成的技术规范,请提供此提示词的优化修改建议.\r\n{technical}\r\n";
        return await GetCompletion(system, prompt);
    }

    /// <summary>
    /// 提示词优化
    /// </summary>
    public async Task<string> PromptOptimize(string prompt)
    {
        var system = "You are a prompt word engineer, and you need to optimize the prompt words. Explain the reasons for optimization.please reply in chinese";
        return await GetCompletion(system, prompt);
    }


    private async Task<string> GetCompletion(string system, string prompt)
    {
        Console.WriteLine(prompt);
        var result = await client.GetCompletion(system, prompt);
        var json = JObject.Parse(result);
        var content = json["choices"][0]["message"]["content"].ToString();
        TextHelper.WriteText("result.txt", content);
        Console.WriteLine(content);
        return content;
    }
}
